package com.dianxun.exam.net;

import android.content.Context;
import android.text.TextUtils;

import com.dianxun.exam.R;
import com.dianxun.exam.entity.ServiceResult;
import com.dianxun.exam.ui.widget.WaitDialog;
import com.dianxun.exam.utils.ToastUtil;
import com.google.gson.Gson;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.download.DownloadListener;
import com.yanzhenjie.nohttp.download.DownloadQueue;
import com.yanzhenjie.nohttp.download.DownloadRequest;
import com.yanzhenjie.nohttp.error.NetworkError;
import com.yanzhenjie.nohttp.error.NotFoundCacheError;
import com.yanzhenjie.nohttp.error.TimeoutError;
import com.yanzhenjie.nohttp.error.URLError;
import com.yanzhenjie.nohttp.error.UnKnownHostError;
import com.yanzhenjie.nohttp.rest.OnResponseListener;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.RequestQueue;
import com.yanzhenjie.nohttp.rest.Response;

import java.util.Map;

public class CallServer {

    // 测试
    public static final String BASE_URL = "http://192.168.1.100/exam/api?v=1.0&format=json&method=";
    public static final String FILE_URL = "http://192.168.1.100:80/tiku/tikuData.txt";

//    public static final String BASE_URL = "http://192.168.10.125/exam/api?v=1.0&format=json&method=";
//    public static final String FILE_URL = "http://192.168.10.125:80/tiku/tikuData.txt";

    // 正式
//    public static final String BASE_URL = "http://192.168.1.100/exam/api?v=1.0&format=json&method=";
//    public static final String BASE_URL = "http://192.168.2.100/exam/api?v=1.0&format=json&method=";

    private static CallServer instance;

    public static CallServer getInstance() {
        if (instance == null)
            synchronized (CallServer.class) {
                if (instance == null)
                    instance = new CallServer();
            }
        return instance;
    }

    private RequestQueue mRequestQueue;
    private DownloadQueue mDownloadQueue;

    private CallServer() {
        mRequestQueue = NoHttp.newRequestQueue(5);
        mDownloadQueue = NoHttp.newDownloadQueue(1);
    }

    /**
     * http get
     *
     * @param what
     * @param url
     * @param msg
     * @param callBack
     * @param rspCls
     */
    public void request(final Context context, int what, final String url, Map<String, Object> map, final String msg, final HttpListener<ServiceResult> callBack, final Class<?> rspCls) {
        // 创建请求对象。
        Request<String> request = NoHttp.createStringRequest(BASE_URL + url, RequestMethod.POST);
        request.setConnectTimeout(10 * 1000);
        request.setReadTimeout(5 * 60 * 1000);
        if (map != null) {
            request.add(map);
        }

        mRequestQueue.add(what, request, new OnResponseListener<String>() {

            WaitDialog mWaitDialog;

            @Override
            public void onSucceed(int what, Response<String> response) {
                String result = response.get();
                ServiceResult rsp = null;
                try {
                    Gson gson = new Gson();
                    rsp = (ServiceResult) gson.fromJson(result, rspCls);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (callBack != null)
                    if (rsp != null) {
                        callBack.onSucceed(rsp);
                    } else {
                        ToastUtil.toast(R.string.error_data);
                        callBack.onFailed();
                    }
            }

            @Override
            public void onStart(int what) {
                // 请求开始，这里可以显示一个dialog
                if (!TextUtils.isEmpty(msg)) {
                    mWaitDialog = new WaitDialog(context);
                    mWaitDialog.setMessage(msg);
                    mWaitDialog.show();
                }
            }

            @Override
            public void onFinish(int what) {
                // 请求结束，这里关闭dialog
                if (mWaitDialog != null && mWaitDialog.isShowing())
                    mWaitDialog.dismiss();
            }

            @Override
            public void onFailed(int what, Response<String> response) {
                // 请求失败
                Throwable exception = response.getException();
                if (exception instanceof NetworkError) {// 网络不好
                    ToastUtil.toast(R.string.error_please_check_network);
                } else if (exception instanceof TimeoutError) {// 请求超时
                    ToastUtil.toast(R.string.error_timeout);
                } else if (exception instanceof UnKnownHostError) {// 找不到服务器
                    ToastUtil.toast(R.string.error_not_found_server);
                } else if (exception instanceof URLError) {// URL是错的
                    ToastUtil.toast(R.string.error_url_error);
                } else if (exception instanceof NotFoundCacheError) {
                    // 这个异常只会在仅仅查找缓存时没有找到缓存时返回
                    ToastUtil.toast(R.string.error_not_found_cache);
                } else {
                    ToastUtil.toast(R.string.error_unknow);
                }
                Logger.e("错误：" + exception.getMessage());
                callBack.onFailed();
            }
        });
    }

    public void download(int what, DownloadRequest request, DownloadListener listener) {
        mDownloadQueue.add(what, request, listener);
    }
}
